/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */

package com.example.soscall.utils;

import static com.example.soscall.Constans.CALL_ACTIVITY_ACTION;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.ecarx.common.BaseApplication;
import com.ecarx.common.RxUtils;
import com.ecarx.xui.adaptapi.oncall.Call;
import com.ecarx.xui.adaptapi.oncall.OnCall;
import com.ecarx.xui.adaptapi.oncall.OnCall.ICallListener;
import com.example.soscall.Constans;
import com.example.soscall.MyApplication;
import com.example.soscall.R;
import com.example.soscall.activity.CallActivity;
import com.example.soscall.bean.EventMsg;
import com.example.soscall.PhoneLiveData;

import org.greenrobot.eventbus.EventBus;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.PublishSubject;


public class CallHelper {

    private static String TAG = "CallHelper-->";

    private volatile static CallHelper sCallHelper;
    private PublishSubject<String> toCallActivitySubject;
    public PhoneLiveData getPhoneLiveData() {
        return phoneLiveData;
    }

    private PhoneLiveData phoneLiveData;
    private static Integer[] status = {Call.CALL_STATUS_IDLE, Call.CALL_STATUS_START_FAILED, Call.CALL_STATUS_CONNECT_FAILED
            , Call.CALL_STATUS_DIAL_FAILED, Call.CALL_STATUS_DATA_UPLOAD_FAILED, Call.CALL_STATUS_REJECTED
            , Call.CALL_STATUS_CALLBACK_REJECTED, Call.CALL_STATUS_HANGING_UP, Call.CALL_STATUS_END};


    public static CallHelper getInstance() {
        if (null == sCallHelper) {
            synchronized (CallHelper.class) {
                if (null == sCallHelper) {
                    sCallHelper = new CallHelper();
                }
            }
        }
        return sCallHelper;
    }

    private OnCall mOnCall;
    private Call currentCall;
    private ICallListener mCallListener;

    private CallHelper() {
        initOnCall();
    }

    private void initOnCall() {
        if (mOnCall == null) {
            mOnCall = OnCall.create(MyApplication.sApp);
        }
        if (mOnCall != null) {
            currentCall = mOnCall.getCurrentCall();
        }
        toCallActivitySubject = PublishSubject.create();
        toCallActivitySubject.throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::startCallActivity, Throwable::printStackTrace);
        phoneLiveData= MyApplication.sApp.getAppViewModelProvider().get(PhoneLiveData.class);
        phoneLiveData.getPhoneState().observeForever(state->{
            switch (state) {
                case Call.CALL_STATUS_IDLE:
                    if(isCallActivityNow()){
                        BaseApplication.bApp.getActivityControl().getCurrentAtivity().finish();
                    }
                    break;
                case Call.CALL_STATUS_IN_ECALL_CALLBACK:
                case Call.CALL_STATUS_DATA_UPLOADING:   //数据上传中
                case Call.CALL_STATUS_IN_COMING_CALL:   //来电
                case Call.CALL_STATUS_RINGING:  //对方响铃中
                case Call.CALL_STATUS_DIALING:   //拨号中
                case Call.CALL_STATUS_CONNECTING:  //数据通路连接中
                case Call.CALL_STATUS_CALL_CONNECTED: //通话连接成功
                case Call.CALL_STATUS_OFFHOOK:  //摘机
                    BluetoothUtil.closeBluetooth();
                    Log.d(TAG, "onNext1: "+state);
                    if(!isCallActivityNow()){
                        Log.d(TAG, "onNext: "+state);
                        toCallActivitySubject.onNext("");
                    }
                    break;
                case Call.CALL_STATUS_START_FAILED:  //开启失败
                case Call.CALL_STATUS_CONNECT_FAILED:  //数据通路连接失败
                case Call.CALL_STATUS_DIAL_FAILED://拨号失败
                case Call.CALL_STATUS_DATA_UPLOAD_FAILED://no use  数据上传失败
                case Call.CALL_STATUS_REJECTED://no use  对方拒接
                case Call.CALL_STATUS_CALLBACK_REJECTED://no use 对方忙线
                case Call.CALL_STATUS_BUSY://no use   对方忙线
                case Call.CALL_STATUS_HANGING_UP://no use  正在挂断
                case Call.CALL_STATUS_END: //通话结束
                    BluetoothUtil.openBluetooth();
                    if(isCallActivityNow()){
                        RxUtils.delayDo(3, TimeUnit.SECONDS,(result, data) -> {
                            if(isCallActivityNow()){
                                BaseApplication.bApp.getActivityControl().getCurrentAtivity().finish();
                            }
                        });
                    }
                    setCallSeconds(0);
                    break;
                case Call.CALL_STATUS_NOT_SUBSCRIBED://no use  the call is not subscribed
                    if(isCallActivityNow()){
                        RxUtils.delayDo(3, TimeUnit.SECONDS,(result, data) -> {
                            if(isCallActivityNow()){
                                BaseApplication.bApp.getActivityControl().getCurrentAtivity().finish();
                            }
                        });
                    }
                    Toast.makeText(MyApplication.sApp, R.string.oncall_unsubscribed_tip, Toast.LENGTH_LONG).show();
                    break;
//            case Call.CALL_STATUS_IN_ECALL_RESCUE_INFO:
//                if (mOnCall != null) {
//                    int rescueTime = mOnCall.getETARescue();
//                    if (rescueTime > 0) {
//                        WindowUtils.showRescueWindow(MyApplication.sApp, callType, rescueTime);
//                    }
//                }
//                break;

                default:
                    break;
            }
        });
    }

    private boolean isCallActivityNow(){
        return BaseApplication.bApp.getActivityControl().contains(CallActivity.class);
    }

    private void startCallActivity(String s){
        Log.d(TAG, "startCallActivity: ");
                Intent intent = new Intent();
                intent.setAction(CALL_ACTIVITY_ACTION);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                MyApplication.sApp.startActivity(intent);



    }
    public Call getCurrentCall() {
        return currentCall;
    }

    public void startECall() {
//
//        if (!checkConnectState()) {
//            onCallStatusChangedUIThread(Call.CALL_TYPE_ECALL, Call.CALL_STATUS_START_FAILED);
//        }
        if (mOnCall != null) {
            mOnCall.startCall(Call.CALL_TYPE_ECALL);
        }
    }

    public void startBCall() {
//
//        if (!checkConnectState()) {
//            onCallStatusChangedUIThread(Call.CALL_TYPE_ECALL, Call.CALL_STATUS_START_FAILED);
//        }
        if (mOnCall != null) {
            mOnCall.startCall(Call.CALL_TYPE_BCALL);
        }
    }

    public void unregisterCallListener() {
        if (mCallListener != null) {
            mOnCall.unregisterCallListener(mCallListener);
        }
    }

    public void registerCallListener() {
        mOnCall.registerCallListener(getStateListener());
    }

    public void onCallStatusChangedUIThread(final int callType, final int status) {
        phoneLiveData.setCallType(callType);
        phoneLiveData.setPhoneState(status);
    }


    private ICallListener getStateListener() {
        if (null == mCallListener) {
            mCallListener = new ICallListener() {
                @Override
                public void onCallCreate(Call call) {
                    currentCall = call;
                }

                @Override
                public void onCallStatusChanged(final int callType, final int status) {

                    Handlers.runOnUiThread(() -> {
                        onCallStatusChangedUIThread(callType, status);
                    });

                }
            };
        }
        return mCallListener;
    }

    private static int mCallSeconds = 0;

    public void setCallSeconds(int seconds) {
        mCallSeconds = seconds;
    }

    public int getmCallSeconds() {
        return mCallSeconds;
    }

    public Call getTBoxCall() {
        //如果mOnCall为空，直接返回null
        if (mOnCall == null) {
            return null;
        }
        Call currentCall = mOnCall.getCurrentCall();
        if (null != currentCall) {
        }
        return currentCall;
    }

    public boolean existCall() {
        Call currentCall = mOnCall.getCurrentCall();
        if (currentCall != null) {
            return currentCall.getStatus() != Call.CALL_STATUS_END;
        }
        return false;
    }

    public int getTBoxCallType() {
        Call call = getTBoxCall();
        if (call != null) {
            return call.getType();
        }
        return -1;
    }

    public int getTBoxCallSatus() {
        Call call = getTBoxCall();
        if (call != null) {
            return call.getStatus();
        }
        return -1;
    }

    public void endCall() {
        Call call = getTBoxCall();
        if (call != null) {
            call.end();
        }
    }

    public void acceptCall() {
        Call call = getTBoxCall();
        if (call != null) {
            call.accept();
        }
    }

    public int getCallDuration() {
        Call call = getTBoxCall();
        int duration = -1;
        try {
            if (call != null) {
                duration = call.getDuration();
            }
            return duration;
        } catch (Exception e) {
        }
        return duration;
    }

    public void activiteICall(int callType) {
        if (mOnCall != null) {
            mOnCall.startCall(Call.CALL_TYPE_ICALL);
        }
    }

    public void activiteBCall(int callType) {
        if (mOnCall != null) {
            mOnCall.startCall(Call.CALL_TYPE_BCALL);
        }
    }

    //判断蓝牙是否连接
    private boolean hasBtConnect() {
        return BluetoothUtil.isBluetoothConnected();
    }


    /**
     * 判断Bcall是否是在拨状态
     *
     * @return
     */
    public static boolean isOpenBcall() {

        boolean isCall = Arrays.asList(status).contains(CallHelper.getInstance().getTBoxCallSatus());
        return CallHelper.getInstance().getTBoxCallType() == Call.CALL_TYPE_BCALL && !isCall;

//        return  CallHelper.getInstance().getTBoxCallType() == Call.CALL_TYPE_BCALL  &&
//                (WindowUtils.getCallWindowType() == WindowUtils.ViewType.MINISIZE ||
//                        WindowUtils.getCallWindowType() == WindowUtils.ViewType.LITTLE );
    }


    /**
     * 判断Ecall是否是在拨状态
     *
     * @return
     */
    public static boolean isOpenEcall() {


        boolean isCall = Arrays.asList(status).contains(CallHelper.getInstance().getTBoxCallSatus());
        return CallHelper.getInstance().getTBoxCallType() == Call.CALL_TYPE_ECALL && !isCall;
    }


    /**
     * 判断Ecall是否正在处理显示
     *
     * @return
     */
    public static boolean isHangUpEnabled() {
        return CallHelper.getInstance().getTBoxCallType() == Call.CALL_TYPE_ECALL;
    }


    public void doTestCallStatusChanged(final int callType, final int status) {
        getStateListener().onCallStatusChanged(callType, status);
    }

}
